package com.jack.concurrency;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by zhang_j on 2019/12/3
 * - ReentrantLock更加灵活，提供了超时获取锁，可中断锁。提供了非公平锁和公平锁，而synchronized仅仅是非公平锁
 * - 用法上，ReentrantLock必须手动释放锁，并且只能修饰代码块。而synchronized不用手动释放锁，除此之外可以修饰方法。
 * - 使用synchronized的线程会被block住，而ReentrantLock的线程则是进入waiting状态
 */
public class MyReentrantLock {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyReentrantLock.class);
    static ReentrantLock lock = new ReentrantLock(false);

    public static void main(String[] args) {
//        syncTest();
        lockTest();
    }

    public static void syncTest(){
        for(int i=0;i<10;i++){
            new Thread(()->{
               synchronized (lock){
                   System.out.println("sync"+Thread.currentThread().getName() + "开始锁定");
                   try{
                       Thread.sleep(2*1000);
                   }catch (Exception e){
                       e.printStackTrace();
                   }finally {
                       System.out.println("sync"+Thread.currentThread().getName() + "解锁");
                   }
               }
            }).start();
        }
    }

    public static void lockTest(){
        for(int i=0;i<10;i++){
            new Thread(()->{
                lock.lock();
                System.out.println("lock"+Thread.currentThread().getName() + "开始锁定");
                try{
                    Thread.sleep(2*1000);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    System.out.println("lock"+Thread.currentThread().getName() + "解锁");
                    lock.unlock();
                }

            }).start();
        }
    }
}
